import dayjs from "dayjs";
import { Loading } from "element-ui";
import duration from "dayjs/plugin/duration";
dayjs.extend(duration);

function dayjsIns(val = new Date()) {
  // dayjs('2019-01-25').format('DD/MM/YYYY')
  return dayjs(val);
}

// 迭代递归法：深拷贝对象与数组
/* function deepClone(obj) {
  if (!isObject(obj)) {
      throw new Error('obj 不是一个对象！')
  }

  let isArray = Array.isArray(obj)
  let cloneObj = isArray ? [] : {}
  for (let key in obj) {
      cloneObj[key] = isObject(obj[key]) ? deepClone(obj[key]) : obj[key]
  }

  return cloneObj
} */

/**
 * @param {string} type
 * @returns {Date}
 */
function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

function getUrlKey(name) {
  return (
    decodeURIComponent(
      (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
        location.href
      ) || [, ""])[1].replace(/\+/g, "%20")
    ) || null
  );
}

function UniqueArr(array) {
  var n = []; //一个新的临时数组
  //遍历当前数组
  for (var i = 0; i < array.length; i++) {
    //如果当前数组的第i已经保存进了临时数组，那么跳过，
    //否则把当前项push到临时数组里面
    if (n.indexOf(array[i]) == -1) {
      n.push(array[i]);
    }
  }
  return n;
}

function BMPGL(ak) {
  return new Promise(function (resolve, reject) {
    window.init = function () {
      // eslint-disable-next-line
      resolve(BMapGL);
    };
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = `http://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=init`;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

function getTabname(params, name) {
  var routeTab = "";

  function Tabname(params, name) {
    for (var i = 0; i < params.length; i++) {
      if (params[i].id == name) {
        routeTab = params[i].description;
        return;
      } else {
        if (params[i].children.length != 0) {
          Tabname(params[i].children, name);
        }
      }
    }
  }
  Tabname(params, name);
  return routeTab;
}

function sortArr(arr, obj) {
  if (obj) {
    for (var i = 0; i < arr.length - 1; i++) {
      //每一轮比较要比多少次
      for (var j = 0; j < arr.length - 1 - i; j++) {
        //如果第一个比第二个大，就交换他们两个位置
        if (arr[j].obj > arr[j + 1].obj) {
          var temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
        }
      }
    }
  } else {
    for (var i = 0; i < arr.length - 1; i++) {
      //每一轮比较要比多少次
      for (var j = 0; j < arr.length - 1 - i; j++) {
        //如果第一个比第二个大，就交换他们两个位置
        if (arr[j] > arr[j + 1]) {
          var temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
        }
      }
    }
  }
  console.log(arr);
}

// 浏览器缓存
function setlocalStorage(key, value) {
  window.localStorage.setItem(key, window.JSON.stringify(value));
}
function getlocalStorage(key) {
  return window.JSON.parse(window.localStorage.getItem(key));
}
function removelocalStorage(key) {
  window.localStorage.removeItem(key);
}
function setsessionStorage(key, value) {
  window.sessionStorage.setItem(key, window.JSON.stringify(value));
}
function getsessionStorage(key) {
  return window.JSON.parse(window.sessionStorage.getItem(key));
}
function removesessionStorage(key) {
  window.sessionStorage.removeItem(key);
}
function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

// loading
function LoadingIns() {
  return Loading.service({
    lock: true,
    text: "Loading",
    spinner: "el-icon-loading",
  });
}

// 文件下载
function downloadFile(res,fileName,fileType) {
  let {headers,data} = res
  if(!fileName){
    let disposition = res.headers['content-disposition'];
    let str = strSplit(disposition,";",1);
    fileName = strSplit(str,"=",1);
    fileName = window.decodeURI(fileName)
  }
  if(!fileType){
    fileType = headers['content-type']
  }

  var blob = new Blob([data], {
    type: fileType
  });
  if ('download' in document.createElement('a')) {
      var downloadElement = document.createElement('a');
      var href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = fileName; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
  } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName);
  }
}

// 字符分割
function strSplit(str,symbol,index){
  let sArr = str.split(symbol)

  if(sArr[index]) {
    return sArr[index]
  }
  return str
}
export default {
  getTime,
  GetQueryString,
  getUrlKey,
  deepClone,
  UniqueArr,
  BMPGL,
  getTabname,
  sortArr,
  setlocalStorage,
  getlocalStorage,
  removelocalStorage,
  setsessionStorage,
  getsessionStorage,
  removesessionStorage,
  clone,
  dayjsIns,
  LoadingIns,
  downloadFile,
  strSplit
};
